<template>
	<view class="uni-list list-pd">
		<view class="uni-list-cell cell-pd">
			<view class="uni-uploader">
				<view class="uni-uploader-head">
					<view class="uni-uploader-title">点击可预览选好的图片</view>
					<view class="uni-uploader-info">{{imageList.length}}/{{count}}</view>
				</view>
				<view class="uni-uploader-body">
					<view class="uni-uploader__files">
						<block v-for="(image,index) in imageList" :key="index">
							<view class="uni-uploader__file">
								<image class="uni-uploader__img" :src="image.src" :data-src="image.src"
									:data-id="image.id" @tap="previewImage">
								</image>
							</view>
						</block>
						<view v-if="imageList.length!=count" class="uni-uploader__input-box">
							<view class="uni-uploader__input" @tap="chooseImage"></view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import permision from "@/common/permission.js"
	import fileservice from '../../myservice/fileservice.js'

	var sourceType = [
		['camera'], //拍照
		['album'], //相册
		['camera', 'album'] //拍照或相册
	]
	var sizeType = [
		['compressed'], //压缩
		['original'], //原图
		['compressed', 'original'] //压缩或原图'
	]
	export default {
		data() {
			return {
				imageList: [],
				phoneIds: []
			}
		},
		props: {
			count: {
				type: Number,
				default: 1,
				//required: false,
			},
			sizeTypeIndex: {
				type: Number,
				default: 2,
				//required: false,
			},
			sourceTypeIndex: {
				type: Number,
				default: 2,
				//required: false,
			},
			images: {
				type: Object,
				default: () => {
					return {
						value:[]
					};
				},
				required: true
			}
		},
		methods: {
			chooseImage: async function() {
				// #ifdef APP-PLUS
				// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
				if (this.sourceTypeIndex !== 2) {
					let status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
				}
				// #endif

				if (this.imageList.length === this.count) {
					let isContinue = await this.isFullImg();
					console.log("是否继续?", isContinue);
					if (!isContinue) {
						return;
					}
				}
				var that = this;
				uni.chooseImage({
					sourceType: sourceType[this.sourceTypeIndex],
					sizeType: sizeType[this.sizeTypeIndex],
					count: this.count - this.imageList.length,
					success: (res) => {
						console.log(JSON.stringify(res))
						//that.imageList = this.imageList.concat(res.tempFilePaths);
						//上传图片到服务器
						res.tempFilePaths.map((value, index) => {
							fileservice.uploadImage(value).then(res => {
								console.log(JSON.stringify(res))
								if (res.statusCode == 200) {
									var data = JSON.parse(res.data);
									that.phoneIds.push(data.Id)
									var da = {
										"id": data.Id,
										"src": value
									};
									that.imageList.push(da);
									if (that.count == 1) {
										that.images.value = da.id
									} else {
										that.images.value.push(da.id);
									}
								} else {
									uni.showToast({
										title: res.errMsg,
										icon: 'none'
									});
								}
							})
						})
					},
					fail: (err) => {
						console.log("err: ", err);
						// #ifdef APP-PLUS
						if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
							this.checkPermission(err.code);
						}
						// #endif
						// #ifdef MP
						if (err.errMsg.indexOf('cancel') !== '-1') {
							return;
						}
						uni.getSetting({
							success: (res) => {
								let authStatus = false;
								switch (this.sourceTypeIndex) {
									case 0:
										authStatus = res.authSetting['scope.camera'];
										break;
									case 1:
										authStatus = res.authSetting['scope.album'];
										break;
									case 2:
										authStatus = res.authSetting['scope.album'] && res
											.authSetting['scope.camera'];
										break;
									default:
										break;
								}
								if (!authStatus) {
									uni.showModal({
										title: '授权失败',
										content: 'Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting()
											}
										}
									})
								}
							}
						})
						// #endif
					}
				})
			},
			async checkPermission(code) {
				let type = code ? code - 1 : this.sourceTypeIndex;
				let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
					await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
						'android.permission.READ_EXTERNAL_STORAGE');

				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: "没有开启权限",
						confirmText: "设置",
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					})
				}

				return status;
			},
			isFullImg: function() {
				var that = this;
				return new Promise((res) => {
					uni.showModal({
						content: "已经有" + that.count + "张图片了,是否清空现有图片？",
						success: (e) => {
							if (e.confirm) {
								this.imageList = [];
								res(true);
							} else {
								res(false)
							}
						},
						fail: () => {
							res(false)
						}
					})
				})
			},

			previewImage: function(e) {
				console.log(JSON.stringify(e))
				var src = e.target.dataset.src
				this.imageList = this.imageList.filter(item => item["src"] != src);
				var id = e.target.dataset.id;
				this.phoneIds = this.phoneIds.filter(item => item != id);
				this.images.value=this.images.value.filter(item=>item!=id);
				// uni.previewImage({
				// 	current: current,
				// 	urls: this.imageList
				// })
			},

			getImageList: function() {
				if (this.phoneIds.length < 1) {
					return "";
				} else {
					if (this.count == 1) {
						return this.phoneIds[0];
					} else {
						return this.phoneIds;
					}
				}
			}
		}
	}
</script>

<style>
	.cell-pd {
		padding: 22rpx 30rpx;
	}

	.list-pd {
		margin-top: 50rpx;
	}
</style>
